package middleware

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	"github.com/mitchellh/mapstructure"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"group-card/common/request"
	"group-card/common/tool"
	"net/http"
)

type CheckUrlMiddleware struct {
	Redis *redis.Redis
}

func NewCheckUrlMiddleware(redis *redis.Redis) *CheckUrlMiddleware {
	return &CheckUrlMiddleware{
		Redis: redis,
	}
}

func (m *CheckUrlMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		//admin, err := m.VerifyToken(r.Header.Get("jwt_token"))
		//if err != nil {
		//	httpx.Error(w, err)
		//	return
		//}
		//tool.GLogLine(admin)
		//
		//r.Header.Add(constant.LoginKey, admin)

		next(w, r)
	}
}

func (m *CheckUrlMiddleware) VerifyToken(token string) (string, error) {
	if token == "" {
		return "", errors.New("请登录")
	}

	claims := jwt.MapClaims{}
	_, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
		return []byte("0ZNIiT2pVlFsKcXmiIkCMn00ftCzjJNW"), nil
	})
	if err != nil {
		return "", errors.New("请登录")
	}

	admin := new(request.CtxAdmin)
	err = mapstructure.Decode(claims, &admin)
	if err != nil {
		return "", errors.New("请登录")
	}
	for key, value := range claims {
		if key == "user_id" {
			admin.UserId = tool.StrToInt64(fmt.Sprintf("%v", value))
		}
		if key == "role_id" {
			admin.RoleId = tool.StrToInt64(fmt.Sprintf("%v", value))
		}
		if key == "level_num" {
			admin.LevelNum = tool.StrToInt64(fmt.Sprintf("%v", value))
		}
	}
	if admin.UserId <= 0 {
		return "", errors.New("请登录")
	}

	a, _ := json.Marshal(admin)

	return string(a), nil
}
